package com.bruce.phoneFlash;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;
import android.widget.ToggleButton;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;

public class MainActivity extends AppCompatActivity {

    private SharedPreferences sp;
    private SharedPreferences.Editor spe;
    private Spinner spinner;
    private ToggleButton button;
    private Switch mySwitch;
    private Switch smsSwitch;
    private boolean isExit = false;
    private ImageView about;
    private ImageView zan;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sp = getSharedPreferences("flash", MODE_PRIVATE);
        spe = sp.edit();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//需要动态申请权限
            requestPermission();
        }
        initView();
        initEvent();
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void requestPermission() {
        List<String> list = new ArrayList<>();
            /*
             * 相机权限
             */
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) !=
                PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                    Manifest.permission.CAMERA)) {//拒绝后解释权限作用
                Toast.makeText(MainActivity.this, "必须使用相机权限", Toast.LENGTH_LONG).show();
            } else {
                list.add(Manifest.permission.CAMERA);
//                list.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
        }

            /*
             * 闪光灯权限
             */
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.FLASHLIGHT) !=
                PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                    Manifest.permission.FLASHLIGHT)) {//拒绝后解释权限作用
                Toast.makeText(MainActivity.this, "必须使用闪光灯权限", Toast.LENGTH_LONG).show();
            } else {
                list.add(Manifest.permission.FLASHLIGHT);
            }

        }


                        /*
            开机启动
             */
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.RECEIVE_BOOT_COMPLETED) !=
                PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                    Manifest.permission.CAMERA)) {//拒绝后解释权限作用
                Toast.makeText(MainActivity.this, "必须使用开启启动权限", Toast.LENGTH_LONG).show();
            } else {
                list.add(Manifest.permission.RECEIVE_BOOT_COMPLETED);
            }

        }

            /*
            电话权限
             */
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE) !=
                PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                    Manifest.permission.CAMERA)) {//拒绝后解释权限作用
                Toast.makeText(MainActivity.this, "必须读取电话状态权限", Toast.LENGTH_LONG).show();
            } else {
                list.add(Manifest.permission.READ_PHONE_STATE);
            }

        }

            /*
            短信权限
             */
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.RECEIVE_SMS) !=
                PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                    Manifest.permission.CAMERA)) {//拒绝后解释权限作用
                Toast.makeText(MainActivity.this, "必须读取电话状态权限", Toast.LENGTH_LONG).show();
            } else {
                list.add(Manifest.permission.READ_PHONE_STATE);
            }

        }
            /*
            读取短信
             */
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_SMS) !=
                PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                    Manifest.permission.CAMERA)) {//拒绝后解释权限作用
                Toast.makeText(MainActivity.this, "必须读取短信状态权限", Toast.LENGTH_LONG).show();
            } else {
                list.add(Manifest.permission.READ_SMS);
            }

        }
        if (!list.isEmpty()) {

            int length = list.size();

            String[] strings = new String[length];
            int i = 0;
            for (String s : list) {
                strings[i] = s;
                i++;
            }
            requestPermissions(strings, 100);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        for (int i = 0; i < permissions.length; i++) {
            if (grantResults[i] != PERMISSION_GRANTED) {
                Toast.makeText(MainActivity.this, "权限" + permissions[i] + "失败", Toast.LENGTH_LONG).show();
            }
        }
    }

    private void initEvent() {
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                spe.putInt("key", position + 1);
                spe.commit();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Intent intent = new Intent(MainActivity.this, MyService.class);
                if (isChecked) {
                    startService(intent);
                } else {
                    stopService(intent);
                }

            }
        });

        SwitchClickListener listener = new SwitchClickListener();
        smsSwitch.setOnCheckedChangeListener(listener);
        mySwitch.setOnCheckedChangeListener(listener);

        zan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, ZanActivity.class);
                startActivity(intent);
            }
        });

        about.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, AboutActivity.class);
                startActivity(intent);
            }
        });
    }

    private void initView() {
        mySwitch = (Switch) findViewById(R.id.my_switch);
        smsSwitch = (Switch) findViewById(R.id.sms_switch);
        spinner = (Spinner) findViewById(R.id.spinner);
        button = (ToggleButton) findViewById(R.id.but);
        smsSwitch.setChecked(sp.getBoolean("sms", true));
        mySwitch.setChecked(sp.getBoolean("checked", true));


        String[] str = {"正常闪光", "SOS模式", "苹果风格"};
        ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_activated_1, str);
        spinner.setAdapter(adapter);


        spinner.setSelection(sp.getInt("key", 1) - 1);
        about = (ImageView) findViewById(R.id.about);
        zan = (ImageView) findViewById(R.id.zan);
    }

    class SwitchClickListener implements CompoundButton.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            switch (buttonView.getId()) {
                case R.id.my_switch:
                    if (buttonView.isChecked()) {
                        spe.putBoolean("checked", true);
                        Toast.makeText(MainActivity.this, "已开启来电闪光灯", Toast.LENGTH_SHORT).show();
                    } else {
                        spe.putBoolean("checked", false);
                        Toast.makeText(MainActivity.this, "已关闭来电闪光灯", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.sms_switch:
                    if (buttonView.isChecked()) {
                        spe.putBoolean("sms", true);
                        Toast.makeText(MainActivity.this, "已开启短信闪光灯", Toast.LENGTH_SHORT).show();
                    } else {
                        spe.putBoolean("sms", false);
                        Toast.makeText(MainActivity.this, "已关闭短信闪光灯", Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
            spe.commit();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isExit) {
                isExit = true;
                Toast.makeText(MainActivity.this, "再按一次返回桌面", Toast.LENGTH_SHORT).show();
                exit();
            } else {
                finish();
            }
        }
        return false;
    }

    private void exit() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                isExit = false;
            }
        }, 2000);
    }
}
